<template>
  <div class="user_container">
    <div class="user_banner">
      <!-- <div
        class="user_banner_title"
        :style="{
          width: settingStore.publicWidth,
        }"
      >
        个人中心
      </div> -->
      <div class="user_mobile_info">
        <div class="user_mobile_info_box">
          <img v-if="image" :src="image" alt="" />
          <img v-else src="@/assets/user-avatar-mobile.png" alt="" />
          <div class="user_mobile_info_text">
            <div class="user_mobile_info_text_name">
              {{ formData.userName }}
            </div>
            <div class="user_mobile_info_text_phone">
              {{ formData.phone }}
            </div>
          </div>
        </div>
        <div class="user_mobile_info_edit">
          <t-upload
            v-model="files"
            class="user_list_content_box_left_upload"
            accept="image/png,image/jpeg"
            tips=""
            theme="custom"
            :before-upload="beforeUpload"
            action="https://service-bv448zsw-1257786608.gz.apigw.tencentcs.com/api/upload-demo"
          >
            <img src="@/assets/user-edit.png" alt="" />
          </t-upload>
        </div>
      </div>
    </div>
    <div class="user_list">
      <div
        class="user_list_content"
        :style="{
          width: settingStore.publicWidth,
        }"
      >
        <div class="user_list_content_breadcrumb">
          <t-breadcrumb>
            <t-breadcrumb-item to="/dashboard/base"> 首页 </t-breadcrumb-item>
            <t-breadcrumb-item>个人中心</t-breadcrumb-item>
          </t-breadcrumb>
        </div>
        <div class="user_list_content_title">
          <h2>个人中心</h2>
          <h4>Personal Center</h4>
          <img src="@/assets/news-fh.png" alt="" />
        </div>
        <div class="user_list_content_box">
          <div class="user_list_content_box_left">
            <div class="user_list_content_box_left_top">
<!--              <img v-if="image" :src="image" alt="" />
              <img v-else src="@/assets/user-avatar.png" alt="" />
              <t-upload
                v-model="files"
                class="user_list_content_box_left_upload"
                accept="image/png,image/jpeg"
                tips=""
                theme="custom"
                :before-upload="beforeUpload"
                action="https://service-bv448zsw-1257786608.gz.apigw.tencentcs.com/api/upload-demo"
              >
                <t-button class="user_upload_btn user_upload_btn_IMG"
                  >修改图片</t-button
                >
              </t-upload>-->
              <p class="name">{{ formData.userName }}</p>
              <p class="signature">{{ formData.signature }}</p>
            </div>
            <t-divider dashed />
            <div class="user_list_content_box_left_center">
              <img src="@/assets/emial.png" alt="" />
              <img src="@/assets/sj.png" alt="" />
              <img src="@/assets/info.png" alt="" />
            </div>
            <t-divider dashed />

            <div class="user_list_content_box_right_item">
              <div v-if="userFormShow" class="user_info_form">
                <dynamic-form
                  v-model="formData"
                  :form-items="formItems"
                  :form-attribute="formAttribute"
                  @get-form-ref="
                    (formDom) => {
                      formRef = formDom;
                    }
                  "
                />
                <div class="user_info_form_btn">
                  <t-button @click="determine">确定</t-button>
                  <t-button
                    class="cancel-btn"
                    variant="outline"
                    @click="handleClose"
                  >
                    取消
                  </t-button>
                </div>
              </div>
              <div v-else class="user_info_form">
                <div class="user_info_form_data">
                  <div><span>真实姓名：</span>{{ formData.userName }}</div>
<!--                  <div><span>电子邮箱：</span>{{ formData.email }}</div>-->
                  <div><span>身份证号：</span>{{ formData.card }}</div>
                  <div><span>手机号码：</span>{{ formData.phone }}</div>
                </div>
                <t-divider dashed />
                <div class="user_info_form_mobile">
                  <div class="user_info_form_mobile_item">
                    <div class="user_info_form_mobile_label">真实姓名：</div>
                    <div class="user_info_form_mobile_value">
                      {{ formData.userName }}
                    </div>
                  </div>
                  <div class="user_info_form_mobile_item">
                    <div class="user_info_form_mobile_label">手机号码：</div>
                    <div class="user_info_form_mobile_value">
                      {{ formData.phone }}
                    </div>
                  </div>
                  <div class="user_info_form_mobile_item">
                    <div class="user_info_form_mobile_label">电子邮箱：</div>
                    <div class="user_info_form_mobile_value">
                      {{ formData.email }}
                    </div>
                  </div>
                  <div class="user_info_form_mobile_item">
                    <div class="user_info_form_mobile_label">身份证号：</div>
                    <div class="user_info_form_mobile_value">
                      {{ formData.card }}
                    </div>
                  </div>
                </div>
              </div>
              <t-button @click="handleEditUser" class="user_upload_btn"
                >修改资料</t-button
              >
            </div>
          </div>
          <div class="user_list_content_box_right">
            <div class="user_list_content_box_right_item">
              <div class="user_list_content_box_right_item_title">
                <span>我的证书</span>
              </div>
              <div class="user_certificate">
                <div class="user_certificate_div" v-for="item in listBook">
                  <img src="@/assets/zhengshu.png" alt="" />
                  <h3>{{item.course}}</h3>
                  <p>{{item.sendDate}}</p>
                  <div>
                    <a :href="item.url" target="_blank" a class="user_certificate_btn" >预览证书</a>
<!--                    <t-button class="user_certificate_btn">下载证书</t-button>-->
                  </div>
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="user_menu_list">
      <!-- <div class="user_menu_list_item" @click="handleClickDetail('base')">
        <div class="user_menu_list_item_left">
          <img src="@/assets/icon_menu_list_1.png" alt="" />
          <div class="user_menu_list_item_text">基本资料</div>
        </div>
        <div class="user_menu_list_item_right"><ChevronRightIcon /></div>
      </div> -->
      <div
        class="user_menu_list_item"
        @click="handleClickDetail('certificate')"
      >
        <div class="user_menu_list_item_left">
          <img src="@/assets/icon_menu_list_2.png" alt="" />
          <div class="user_menu_list_item_text">我的证书</div>
        </div>
        <div class="user_menu_list_item_right">
          <t-badge :count="zsCuont" :offset="[50, 20]">
            <ChevronRightIcon />
          </t-badge>
        </div>
      </div>
    </div>


    <t-dialog
          class="custom-dialog"
          v-model:visible="dialogTableVisible"
          header=""
          :close-on-overlay-click="false"
          :confirm-btn="null"
          :cancel-btn="null"
          size="large"
          :closeBtn="false"
        >
          <div class="formBox">
            <t-form
              ref="form"
              :rules="FORM_RULES"
              :data="formDataPassrod"
              :colon="true"
              @submit="onSubmit"
            >
              <t-form-item label="密码" name="password">
                <t-input
                  v-model="formDataPassrod.password"
                  type="password"
                  placeholder="请输入内容"
                ></t-input>
                <template #prefix-icon>
                  <lock-on-icon />
                </template>
              </t-form-item>
              <t-form-item label="确认密码" name="confirmPassword">
                <t-input
                  v-model="formDataPassrod.confirmPassword"
                  type="password"
                  placeholder="请输入内容"
                ></t-input>
                <template #prefix-icon>
                  <lock-on-icon />
                </template>
              </t-form-item>
              <t-form-item>
                <t-button theme="primary" type="submit" block>重置密码</t-button>
              </t-form-item>
            </t-form>
          </div>
          <template #footer></template>
        </t-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: "ListBase",
};
</script>

<script setup lang="ts">
import { ChevronRightIcon, EditIcon } from "tdesign-icons-vue-next";
import { onMounted, ref,reactive } from "vue";
import { useRouter, useRoute } from "vue-router";

import {
  COLUMNS,
  formData,
  formAttribute,
  formRef,
  formItems,
  resetFormData,
} from "./constants";
import {
  updateFirstPassword,
} from "@/api/index";
import { DynamicForm } from "@/libs/components/dynamicForm";
import { useSettingStore,useUserStore } from "@/store";
import { data, fetchData } from "./request";
import { myBook,updateMember } from "@/api";
import { TOKEN_NAME, user_info, } from "@/config/global";
import { MessagePlugin } from "tdesign-vue-next";
const files = ref([]);
const route = useRoute();
const router = useRouter();
const settingStore = useSettingStore();
const image = ref("");
const baseImage = new URL("@/assets/user-avatar.png", import.meta.url);
const userFormShow = ref(false);
const zsCuont = ref(2);
const userStore = useUserStore();
formData.value= JSON.parse(localStorage.getItem(user_info));
const listBook= ref( []);
// --------------修改密码
const dialogTableVisible = ref(false);
const FORM_RULES = {
  password: [{ required: true, message: "密码必填" }],
  confirmPassword: [{ required: true, message: "确认密码必填" }],
};
const formDataPassrod = reactive({
  password: "",
  confirmPassword: "",
});

const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    if (formDataPassrod.password != formDataPassrod.confirmPassword) {
      MessagePlugin.warning("密码不一致");
      return;
    }
    console.log(formDataPassrod.password);
    updateFirstPassword({ password: formDataPassrod.password })
      .then((e) => {
        localStorage.setItem("loginTime", 1);
        MessagePlugin.success("提交成功");
        dialogTableVisible.value = false;
      })
      .catch((e) => {
        if ((e.code = 401)) {
          localStorage.removeItem(TOKEN_NAME);
          localStorage.removeItem("loginTime");
          const router = useRouter();
          router.push({ path: "login" });
        }
      });
  } else {
    console.log("Validate Errors: ", firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

function alertInitPassWord() {
  // 有token的时候进行判断   后端需要加是否 修改过密码的判断
  var loginTime = localStorage.getItem("loginTime") as unknown;
  if (
    userStore.$state.token != null &&
    userStore.$state.token != "" &&
    loginTime != null &&
      (loginTime == 0 || loginTime == "0")
  ) {
    dialogTableVisible.value = true;
  }
}

// --------------修改密码
const postData = () => {
  var item = localStorage.getItem(TOKEN_NAME);
  if (item==null){
    const router = useRouter();
    router.push({path: "login"});
    return;
  }
  myBook(formData.value).then(e=> {
    listBook.value=e.rows;
    alertInitPassWord();
  }).catch(e=> {
    if (e.code==401){
      localStorage.removeItem(TOKEN_NAME);
      const router = useRouter();
      router.push({path: "login"});
    }
  })
};
const updateInfo = () => {
  var item = localStorage.getItem(TOKEN_NAME);
  if (item==null){
    const router = useRouter();
    router.push({path: "login"});
    return;
  }
  updateMember({email:formData.value.email,phone:formData.value.phone,card:formData.value.card,userName:formData.value.userName}).then(e=> {
    let data = JSON.parse(localStorage.getItem(user_info));
    data.email=formData.value.email;
    data.phone=formData.value.phone;
    data.card=formData.value.card;
    data.userName=formData.value.userName;
    localStorage.setItem(user_info,JSON.stringify(data));
    MessagePlugin.success("更新成功！");
    userFormShow.value = false;
  }).catch(e=> {
    if (e.code=401){
      localStorage.removeItem(TOKEN_NAME);
      const router = useRouter();
      router.push({path: "login"});
    }
  })
};
onMounted(() => {
  // 调用list接口
  postData()
});
const determine = async () => {
  const result = await formRef.value?.validate();

  if (result !== true) {
    return;
  }
  // 调用保存接口
  if (userFormShow.value) {
    updateInfo();
  }
  return;
};
const handleClose = () => {
  userFormShow.value = false;
  // resetFormData();
  formData.value= JSON.parse(localStorage.getItem(user_info));
  // fetchData();
};
const handleFail = ({ file }) => {
  // MessagePlugin.error(`文件 ${file.name} 上传失败`);
};
const beforeUpload = (file) => {
  if (file.size > 5 * 1024 * 1024) {
    // MessagePlugin.warning('上传的图片不能大于5M');
    return false;
  }
  return true;
};
// 编辑
const handleEditUser = () => {
  userFormShow.value = !userFormShow.value;
};
// 预览
const handleClickView = (row) => {
  console.log(row);
};
// 下载
const handleClickDwon = (row) => {
  console.log(row);
};
const handleClickDetail = (type) => {
  router.push({
    path: "/userMobile",
    query: { type: type },
  });
};
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
